<template>
  <div class="book-detail">
    <t-card :bordered="false" class="content-card">
      <template #title>
        <t-space size="0">
          <div class="drawer-head" style="height: 36px;">
            <p class="chevron-left" @click="back">
              <icon-font name="chevron-left" size="18px"/>
            </p>
          </div>
          <div>
            <h2 class="card-title">{{ storeInfo.name }}</h2>
            <p class="card-sub-title">入库订单记录</p>
          </div>
        </t-space>
      </template>
      <template #actions>
        <t-space size="8px">
          <t-button @click="handleWarehousing" class="add-btn">
            <p class="flex align-center">
              <i class="iconfont icon-warehousing" style="font-size: 24px;margin-right: 4px"></i>入库
            </p>
          </t-button>
        </t-space>
      </template>

      <div class="filter ">
        <t-space size="12px">
          <t-select style="width: 260px;" v-model="params.status" :options="statusOptions" clearable @change="getData"
                    placeholder="请选择记录状态">
            <template #label>
              <icon-font name="layers" style="color: #000;"/>
            </template>
          </t-select>
          <t-date-range-picker style="width: 260px;" allow-input clearable @change="onChangeDate"/>
          <t-input style="width: 260px;" v-model="params.key" clearable @change="onChangeKey"
                   placeholder="搜索：单号/产品/SN">
            <template #label>
              <icon-font name="search" size="16px" style="color:#000;font-weight: bold;cursor: pointer;"
                         @click="getData"/>
            </template>
          </t-input>
        </t-space>
      </div>

      <div class="pt16">
        <t-table
          rowKey="id"
          :data="lists"
          :columns="columns"
          :stripe="stripe"
          :bordered="bordered"
          :hover="hover"
          :size="size"
          :max-height="maxHeight"
          :table-layout="tableLayout ? 'auto' : 'fixed'"
          :showHeader="showHeader"
          cellEmptyContent="-"
          resizable
          :loading="loading"
          @page-change="pageChange"
          :pagination="pagination"
          :selected-row-keys="selectedRowKeys"
        >
          <template #product_title="{row}">
            <div class="">
              <p class="item-title">{{ row.product_title }}</p>
              <p v-if="row.sn" class="item-sn">S/N:{{ row.sn }}</p>
            </div>
          </template>
          <template #unit_price="{row}">
            <div class="flex align-center">
              <p>{{ row.unit_price ? `￥${row.unit_price}` : '-' }}</p>
            </div>
          </template>
          <template #product_selling_price="{row}">
            <div class="flex align-center">
              <p>{{ row.product_selling_price ? `￥${row.product_selling_price}` : '-' }}</p>
              <t-tooltip v-if="!row.product_selling_price" content="请到产品库设置产品的售价">
                <icon-font name="help-circle" style="margin-left: 6px"></icon-font>
              </t-tooltip>
            </div>
          </template>
          <template #status="{row}">
            <t-tag v-if="row.status === 1" shape="round" variant="light" theme="success">启用</t-tag>
            <t-tag v-else shape="round" variant="light" theme="danger">作废</t-tag>
          </template>
          <template #option="{row}">
            <t-space size="12px">
              <t-link v-if="row.quantity > 0" theme="primary" class="edit-btn-color" hover="color" @click="handleOutbound(row)">出库</t-link>
              <!--<t-link theme="primary" class="edit-btn-color" hover="color" @click="goProductInfo(row)">详情</t-link>-->
              <t-popconfirm v-if="row.status === 1 && row.is_cancel === 1" theme="danger" placement="top-right" confirm-btn="确认" @confirm="handleCancel(row)">
                <template #content>
                  <div class="popconfirm-body">
                    <h3 class="popconfirm-title">作废？</h3>
                    <p>作废后数据将不可恢复！是否作废？</p>
                  </div>
                </template>
              <t-link theme="danger" hover="color">作废</t-link>
              </t-popconfirm>
            </t-space>
          </template>
        </t-table>
      </div>
    </t-card>


    <!-- 产品入库 -->
    <product-warehousing ref="warehousing" :storeId="storeId" @refresh="getList"></product-warehousing>


    <!-- 填写出库信息 -->
    <product-config ref="config" from="detail" :storeId="storeId" @confirm="confirmProduct"></product-config>
  </div>
</template>

<script lang="jsx">
import {IconFont, CalendarIcon, BrowseIcon} from "tdesign-icons-vue";
import IconUAV from "@/components/icon-UAV/index.vue";
import ProductWarehousing from "@/pages/inventory/components/product-warehousing/index.vue";

import {warehouseDetailApi} from "@/api/warehouse";
import {outboundRecordCreateApi, warehousingRecordCancelApi, warehousingRecordListApi} from "@/api/inventory";
import ProductConfig from "@/pages/inventory/components/product-outbound/product-config.vue";

export default {
  name: 'WarehousingHistory',
  components: {
    ProductConfig,
    IconUAV,
    IconFont,
    BrowseIcon,
    ProductWarehousing,
  },
  data() {
    return {
      storeId: '', // 仓库id
      storeInfo: {}, // 仓库信息
      params: {
        page: 1,  // 当前页
        limit: 10,  // 每页条数
        warehouse_id: '', // 仓库id
        key: '',  // 搜索：单号/批号/联系人/经办人
        status: '', // string 可选 状态（-1作废；1启用）
        start_time: '', // string 可选 入库日期范围，yyyy-MM-dd
        end_time: '', // string 可选 入库日期范围，yyyy-MM-dd
      },
      lists: [],
      size: 'medium',
      tableLayout: false,
      stripe: false,
      bordered: false,
      hover: true,
      showHeader: true,
      columns: [
        {colKey: 'id', title: 'ID', align: 'center', width: 56,},
        {colKey: 'product_title', title: '产品标题', minWidth: 260, ellipsis: true},
        {colKey: 'product_unit_title', title: '单位', align: 'center', width: 66},
        {colKey: 'quantity', title: '数量', align: 'center', width: 90},
        {colKey: 'unit_price', title: '入库价格', width: 110},
        {colKey: 'product_selling_price', title: '出售价', width: 110},
        {colKey: 'status', title: '状态', width: 90,},
        {colKey: 'creation_admin', title: '操作员', width: 110,},
        {colKey: 'remark', title: '备注', width: 220, ellipsis: true},
        {colKey: 'record_date', title: '操作时间', width: 120,},
        {colKey: 'option', title: '', fixed: 'right', width: 120},
      ],
      selectedRowKeys: [],
      pagination: {
        defaultCurrent: 1,
        defaultPageSize: 20,
      },
      maxHeight: 472,
      loading: false,

      statusOptions: [
        {label: '启用', value: 1},
        {label: '作废', value: -1},
      ],
      timer: null
    };
  },
  mounted() {
    // 获取屏幕高度 - 顶部高度
    let height = document.documentElement.clientHeight - 244;
    this.maxHeight = height
    window.onresize = () => {
      // 获取屏幕高度 - 顶部高度
      height = document.documentElement.clientHeight - 244;
      this.maxHeight = height
    };
    const {storeId} = this.$route.query
    this.storeId = storeId
    this.params.warehouse_id = storeId
    this.storeInfo = {}
    // 获取仓库详情
    this.getStoreInfo()
    // 获取仓库入库订单记录
    this.getData()
  },
  methods: {
    back() {
      this.$router.go(-1)
    },
    // 获取仓库信息
    getStoreInfo() {
      warehouseDetailApi(this.storeId).then(res => {
        this.storeInfo = res.data
      }).catch(err => {
        console.log('err', err)
      })
    },
    // 入库
    handleWarehousing() {
      this.$refs.warehousing.open()
    },
    // 作废
    handleCancel(row) {
      warehousingRecordCancelApi({id: row.id}).then(res => {
        this.$message.success('作废成功')
        this.getList()
      }).catch(err => {
        console.log('err', err)
      })
    },
    // 出库
    handleOutbound(row) {
      const data = {...row}
      data.title = data.product_title
      this.$refs.config.open(data)
    },
    // 确认出库产品
    confirmProduct(list, prodId) {
      const params = {
        ck_warehouse_id: list[0].ck_warehouse_id, // 出库ID 必需
        rk_warehouse_id: list[0].rk_warehouse_id, // 入库ID 必需
        batch_no: '', // 批次编号 可选
        product_data: JSON.stringify(list),
      }
      outboundRecordCreateApi(params).then(res=> {
        console.log('res', res)
        this.$message.success('出库成功')
        this.getList()
      }).catch(err=> {
        console.log('err', err)
      })
    },
    // 切换日期
    onChangeDate(value, context) {
      this.params.start_time = value[0]
      this.params.end_time = value[1]
      this.getData()
    },
    onChangeKey(value) {
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.getData();
        clearTimeout(this.timer)
      }, 500)
    },
    // 获取数据
    getData() {
      this.pagination.defaultCurrent = 1
      this.getList()
    },
    // 获取列表
    getList() {
      this.loading = true
      this.params.page = this.pagination.defaultCurrent
      warehousingRecordListApi(this.params).then(res => {
        this.pagination.total = res.count
        this.lists = res.data
      }).catch(err => {
      }).finally(() => {
        this.loading = false
      })
    },
    // 切换分页
    pageChange(pageInfo) {
      const {current, defaultCurrent, defaultPageSize,} = pageInfo
      this.pagination.defaultCurrent = current
      this.getList()
    },
  },
}
</script>

<style lang="less" scoped>
.book-detail {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  border-radius: var(--td-radius-medium);
  background-color: #FFFFFF;
}

.item-title {
  font-weight: 500;
}

.item-sn {
  font-size: 14px;
  font-weight: 400;
  line-height: 24px;
  text-align: left;
  color: rgba(0, 0, 0, 0.6);
}

/deep/ .content-card {

  .t-card__header {
    padding: var(--td-comp-paddingTB-xl) var(--td-comp-paddingLR-xl);
    padding-bottom: 0;
  }

  .t-card__body {
    padding: var(--td-comp-paddingTB-l) var(--td-comp-paddingLR-xl) var(--td-comp-paddingTB-m);
  }

  .card-sub-title {
    font-size: 16px;
    font-weight: 400;
    line-height: 24px;
    text-align: left;
    color: #000000;
    padding-top: 8px;
  }
}

/deep/ .filter {
  padding-top: 13px;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .t-input, .t-input.t-is-readonly {
    background-color: #F8F8F8;
  }
}

</style>
